# 导包
import pymysql


class DBUtils:
    def __init__(self):
        self.conn = None
        self.cursor = None
    # 创建数据库连接
    def db_connect(self):
        if self.conn is None:
            self.conn = pymysql.connect(host='121.43.169.97',
                                       port=3306,
                                       user='student',
                                       password='P2P_student_2023',
                                       database='czbk_member',
                                       charset='utf8')
        return self.conn

    # 获取游标对象
    def get_cursor(self):
        if self.cursor is None:
            self.cursor = self.db_connect().cursor()
        return self.cursor

    # 执行操作
    def execute_sql(self, sql):
        try:
            cursor = self.get_cursor()
            cursor.execute(sql)
            if sql.strip().lower().startswith('select'):
                result = cursor.fetchall()
                return result
            else:
                self.conn.commit()
                # 返回受影响的行数
                return cursor.rowcount
        except Exception as e:
            print(f"数据库执行错误：{e}")
            self.conn.rollback()
        finally:
            self.close_cursor()
            self.close_connect()
    def close_cursor(self):
        if self.cursor:
            self.cursor.close()
            self.cursor = None
    # 关闭连接
    def close_connect(self):
        if self.conn:
            self.conn.close()
            self.conn = None

if __name__ == '__main__':
    db = DBUtils()
    print(db.execute_sql("select version()"))
